//
//  SearchViewController.m
//  dhfsAPP
//
//  Created by Devil on 2017/8/7.
//  Copyright © 2017年 Devil. All rights reserved.
//

#import "SearchViewController.h"
#import "fsapp-Swift.h"

static sqlite3 *db;

@interface SearchViewController (){
    NSArray *historyAry;
    NSArray *hotContentAry;
}

@property(strong,nonatomic)SearchHistoryView *searchHistoryView;

@property(strong,nonatomic)SearchContentTableView *tableView;

@end

@implementation SearchViewController
#pragma mark - 懒加载
-(SearchView *)searchView{
    if (!_searchView) {
        _searchView = [[SearchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT(128))];
        
        _searchView.headerView.headerViewDelegate = self;
        _searchView.searchContentTextField.delegate = self;
        
        [_searchView.searchContentTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventAllEditingEvents];
    }
    
    return _searchView;
}

-(SearchHistoryView *)searchHistoryView{
    if (!_searchHistoryView) {
        _searchHistoryView = [[SearchHistoryView alloc] initWithFrame:CGRectMake(0, HEIGHT(128), SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT(128)) HistoryArray:historyAry];
        
        _searchHistoryView.searchHistoryDelegate = self;
    }
    
    return _searchHistoryView;
}

-(SearchContentTableView *)tableView{
    if (!_tableView) {
        _tableView = [[SearchContentTableView alloc] initWithFrame:CGRectMake(0, HEIGHT(128), SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT(128))];
        
        _tableView.searchContentTableViewDelegate = self;
        
        _tableView.hidden = YES;
    }
    
    return _tableView;
}
#pragma mark - 系统自动调用函数
- (void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBarHidden = YES;[super viewWillAppear:false];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self openDataBase];
    [self createTable];
//    [self insterSqlite];
    historyAry = [self searchHistory];
    [self closeDataBase];
    [self getHotContent];
   
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.searchHistoryView];
    [self.view addSubview:self.tableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - HeaderViewDelegate协议实现
-(void)clickHeaderViewBtn{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - 数据库操作
//配置数据库路径,打开数据库
-(void)openDataBase{
    //创建数据库,并打开,获取数据库路径
    NSString *databaseFilePath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //设置数据库的路径和名称
    NSString *dataBasePath = [[NSString alloc] initWithString:[databaseFilePath stringByAppendingPathComponent:@"fsApp.sqlite"]];
    //打开数据库,数据库文件不存在时,自动创建
    if (sqlite3_open([dataBasePath UTF8String], &db) == SQLITE_OK) {
        NSLog(@"sqlite database is opened");
    }else{
        NSLog(@"sqlite database open fail");
    }
}

//创建表
- (void)createTable{
    //sql语句
    /*
     *create table if not exists 如果表不存在时自动创建
     *autoincrement 自增属性
     */
    NSString *createTableSql = @"create table if not exists historyTable(id integer primary key autoincrement,videoID int,videoUrl text,historyContent text)";
    
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [createTableSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据表创建成功");
    }else{
        NSLog(@"创建数据表失败:%s",error);
    }
}

//插入记录
- (BOOL)insertInformationWithVideoID:(NSString *)videoID VideoUrl:(NSString *)videoUrl historyContent:(NSString *)historyContent{
    //sql语句
    NSString *insertSql = [NSString stringWithFormat:@"insert into historyTable(videoID,videoUrl,historyContent) values('%@','%@','%@')",videoID,videoUrl,historyContent];
    //        NSString *insertSql = [NSString stringWithFormat:@"insert into CollectTable(stationName,busName,toWhere) values('110指挥中心','16路','浦南')"];
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据插入成功");
        return YES;
    }else{
        NSLog(@"数据插入失败:%s",error);
        return NO;
    }
    
}

-(void)insterSqlite{
            NSString *insertSql = [NSString stringWithFormat:@"insert into historyTable(videoID,videoUrl,historyContent) values('3','www.baidu.com','风水勘察aaaaaaaaaa')"];
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据插入成功");
    }else{
        NSLog(@"数据插入失败:%s",error);
    }

}

//查询搜索历史
-(NSMutableArray *)searchHistory{
    NSString *searchSql = [NSString stringWithFormat:@"select * from historyTable group by videoID order by id asc"];
    
    //预编译sql语句产生的结果
    sqlite3_stmt *stmt;
    NSMutableArray *historyArray = [[NSMutableArray alloc] init];
    
    if (sqlite3_prepare_v2(db, [searchSql UTF8String], -1, &stmt, NULL) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSLog(@"%@",[NSString stringWithFormat:@"%d",sqlite3_column_int(stmt, 1)]);
            NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)]);
            NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 3)]);
            NSArray *array = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",sqlite3_column_int(stmt, 1)],[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)], [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 3)],nil];
            
            [historyArray addObject:array];
        }
    }else{
        NSLog(@"查询失败");
    }
    
    NSLog(@"%@",historyArray);
    
    return historyArray;
}

//删除表
-(void)deleteTable{
    NSString *dropTable1 = @"DROP TABLE historyTable";
    
    const char *drop_stmt = [dropTable1 UTF8String];
    
    char *errMsg;
    
    if(sqlite3_exec(db, drop_stmt, NULL, NULL, &errMsg)==SQLITE_OK)
        
    {
        
        NSLog(@"删除成功");
        
    }else{
        
        NSLog(@"删除不成功");
        
    }
}

//关闭数据库
-(void)closeDataBase{
    sqlite3_close(db);
}
#pragma mark - 连接服务器
-(void)getHotContent{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/index/hot_search" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if ([responseObject[@"status"] integerValue] == 200)
         {
             NSLog(@"%@",responseObject[@"result"]);
             hotContentAry = responseObject[@"result"];
             [self.searchHistoryView changeHotContentView:hotContentAry];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];

}

-(void)searchContent{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    NSDictionary *parameters = @{
                                 @"search":self.searchView.searchContentTextField.text
                                 };
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/index/search" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if ([responseObject[@"status"] integerValue] == 200) {
             self.tableView.searchContentArray = responseObject[@"result"];
             
             [self.tableView reloadData];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];
}

#pragma mark - SearchHistoryDelegate实现
-(void)deleteHistory{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除历史记录？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
        [self openDataBase];
        [self deleteTable];
        [self createTable];
        historyAry = [self searchHistory];
        [self.searchHistoryView changeHistory:historyAry];
        
        [self closeDataBase];
    }]];
   [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]] ;
    
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)clickHotContent:(int)tag{
    VideoDetailViewController *vc = [[VideoDetailViewController alloc] init:hotContentAry[hotContentAry.count - 1 - tag][@"video_src"] :hotContentAry[hotContentAry.count - tag - 1][@"id"]];
   // self.navigationController.navigationBarHidden = NO;
   // UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:vc animated:true completion:nil];
    //    [self.navigationController pushViewController:nav animated:YES];
 //   [self.navigationController pushViewController:vc animated:true];
    [self openDataBase];
    [self createTable];
    [self insertInformationWithVideoID:hotContentAry[hotContentAry.count - tag - 1][@"id"] VideoUrl:hotContentAry[hotContentAry.count - 1 - tag][@"video_src"] historyContent:hotContentAry[hotContentAry.count - 1 - tag][@"name"]];
    historyAry = [self searchHistory];
    [self.searchHistoryView changeHistory:historyAry];
    
    [self closeDataBase];
    
    
}

-(void)clickHistory:(int)tag{
    VideoDetailViewController *vc = [[VideoDetailViewController alloc] init:historyAry[historyAry.count - tag - 1][1] :historyAry[historyAry.count - tag - 1][0]];
    self.navigationController.navigationBarHidden = NO;
    //[self.navigationController pushViewController:vc animated:true];
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - SearchContentTableViewDelegate实现
-(void)clickItem:(int)tag{
    VideoDetailViewController *vc = [[VideoDetailViewController alloc] init:self.tableView.searchContentArray[tag][@"video_src"] :self.tableView.searchContentArray[tag][@"id"]];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    //    [self.navigationController pushViewController:nav animated:YES];
    self.navigationController.navigationBarHidden = NO;
  [self.navigationController pushViewController:vc animated:true];
    [self openDataBase];
    [self createTable];
    [self insertInformationWithVideoID:self.tableView.searchContentArray[tag][@"id"] VideoUrl:self.tableView.searchContentArray[tag][@"video_src"] historyContent:self.tableView.searchContentArray[tag][@"name"]];
    historyAry = [self searchHistory];
    [self.searchHistoryView changeHistory:historyAry];
    
    [self closeDataBase];
}

#pragma mark - 其他函数
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.searchView.searchContentTextField resignFirstResponder];
}

-(void)textFieldDidChange:(UITextField *)textField{
    
    NSLog(@"%@",textField.text);
    if (textField.text.length > 0)
    {
        [self searchContent];
        
        self.tableView.hidden = NO;
        
    }
    else
    {
        self.tableView.hidden = YES;
    }
}


@end
